"""

   Pubsub envelope subscriber   
 
   Author: Xuhui Han

   This program is a example of target inserting. The target list is writen in the files "./target_file/glade_galaxy_******.dat"
    They contain target name 1, target name 2, RA, Dec. Other observation information is writen in the file "obs_param.json", which 
    is needed for making the observation plan.
  
"""

import sys
import json
import datetime
import time

sys.path.append('./object_generator/')
from object_generator.object_generator import obj_add as obj_insert
from communication_client.communication_client import Client

#__________________________________
def Obs_parameter(json_file):
    "The observation parameters in the static file db_param.json."
    with open(json_file, "r") as read_file:
        data = json.load(read_file)
    return data

def reading_galaxies(galaxies_file):
    e=open(galaxies_file,'r')
    p=0
    linese=['0']
    while True:
        linese[p]=e.readline()
        if not linese[p]: break
        if linese[p][0] != "#":
          p=p+1
          linese.append(p)
    e.close()
    linese = list(filter(None,linese))
    maxrece = len(linese)

    galaxy_id_arr = []
    galaxy_alias_arr = []  
    ra_arr = []
    dec_arr = []
    for n in range(len(linese)):
        galaxy_id=(linese[n].split()[0])
        galaxy_alias=(linese[n].split()[1])
        ra=(float(linese[n].split()[2]))
        dec=(float(linese[n].split()[3]))

        galaxy_id_arr.append(galaxy_id)
        galaxy_alias_arr.append(galaxy_alias)
        ra_arr.append(ra)
        dec_arr.append(dec)
    return(galaxy_id_arr,galaxy_alias_arr,ra_arr,dec_arr)

def func_glade_galaxy_insert_db(glade_id,glade_alias,RA_pointing,dec_pointing):

    telescope_object = 'F60_GALAXY_SURVEY'

    obs_type = 'pointing'

    json_file = './obs_param.json'

    obs_param = Obs_parameter(json_file)

    mode = "observation"

    client = Client('object_generator')

    utc_time  = time.gmtime()
    date_beg = time.strftime('%Y/%m/%d', utc_time)
    date_beg_datetime =  datetime.datetime.strptime(date_beg, "%Y/%m/%d")
    date_end_datetime =  date_beg_datetime + datetime.timedelta(days=int(obs_param[telescope_object]["day_int"]))
    date_end = date_end_datetime.strftime("%Y/%m/%d")    
    date_str = time.strftime('%Y_%m_%d', utc_time)
    outputfile = './logs/'+ date_str + ".dat"
    g = open(outputfile,'w')
    for i in range(len(glade_id)):
        Obj_name = glade_id[i]
        Obj_alia = glade_alias[i]
        Objsour = 'glade_galaxy'
        Observer = obs_param[telescope_object]["Observer"]
        Group_ID = obs_param[telescope_object]["Group_ID"]
        Unit_ID = obs_param[telescope_object]["Unit_ID"]
        ObjRA = RA_pointing[i]
        ObjDEC = dec_pointing[i]
        ObjEpoch = 2000
        ObjError = '0.0|0.0'
        ObjRank = 0
        Obs_type = obs_param[telescope_object]["Obs_type"]
        Obs_Strat = obs_param[telescope_object]["Obs_Strat"]
        date_beg = date_beg
        date_end = date_end
        day_int = obs_param[telescope_object]["day_int"]
        ImgType = obs_param[telescope_object]["ImgType"]
        filter_r = obs_param[telescope_object]["filter"]
        expdur = obs_param[telescope_object]["expdur"]
        delay = obs_param[telescope_object]["delay"]
        frmcnt = obs_param[telescope_object]["frmcnt"]
        run_name = 1
        priority = obs_param[telescope_object]["priority"]

        write_line = "obj_name=%s objalia1=%s objsour=%s observer=%s objra=%s objdec=%s objepoch=%s \
objerror=%s objrank=%s group_id=%s unit_id=%s obs_type=%s \
obs_strat=%s date_beg=%s date_end=%s day_int=%s imgtype=%s \
filter=%s expdur=%s delay=%s frmcnt=%s priority=%s \
run_name=%s mode=%s\n" % \
         (Obj_name, Obj_alia, Objsour, Observer, ObjRA, ObjDEC, ObjEpoch, \
         ObjError,ObjRank, Group_ID, Unit_ID, Obs_type, \
         Obs_Strat,date_beg, date_end, day_int, ImgType, \
         filter_r,expdur, delay, frmcnt, priority, \
         run_name,mode)

        g.write(write_line)

        obj_insert(write_line)

    g.close

    client.Send()
    print('the log file ' +outputfile+ 'is saved. ')

galaxies_file = './target_file/glade_galaxy_210301.dat'
print('reading galaxies from ',galaxies_file)
glade_id,glade_alias,RA_pointing,dec_pointing = reading_galaxies(galaxies_file)
func_glade_galaxy_insert_db(glade_id,glade_alias,RA_pointing,dec_pointing)
